<?php


namespace app\impl;


use app\common\business\Message;
use app\common\lib\HisData;
use app\common\lib\ZhyxBeanstalkd;
use app\common\lib\ZhyxMongo;
use app\common\model\BaseModel;
use app\common\model\PatientInfo;
use app\common\model\SmsRecord;
use app\common\utils\Sms;
use app\common\utils\Str;
use app\interfaces\Task;
use catchAdmin\sms\model\SmsTemplate;
use catchAdmin\smstag\model\SmsTag;
use catchAdmin\smstopic\model\SmsTopic;
use catcher\base\CatchModel;
use think\Log;

class SendSms implements Task
{

    public function run(array $data, string $taskId): ?bool
    {

        $telephoneArr = [];
        $patientIdArr = [];
        $businessData = [];
        $status = 0;
        $isCustom = false;
        //根据模板ID获取模板信息
        $templateInfo = (new SmsTemplate())->getTemplateById($data["template_id"]);

        if (empty($templateInfo)) {
            return true;
        }
        try {
            if (isset($data["customer_content"]) && !empty($data["customer_content"])) {
                $isCustom = true;
                $content = $data["customer_content"];
            } else {

                if ($templateInfo["model"] !== "Common" && !empty($data["business_id"])) {
                    $modelName = "app\\common\\model\\" . ucfirst($templateInfo["model"]);
                    $businessData = (new $modelName())->find($data["business_id"]);
                }

                //判断模板中的内容是否需要转换变量操作
                $content = $templateInfo["content"];
                $pattern = ' /(@.*@)/Ui';
                preg_match_all($pattern, $content, $match);
            }

            //说明不需要替换短信
            if ($isCustom || empty($match[0])) {
                //获取全部患者
                $patientList = (new PatientInfo())->getPatientListByUids($data["users"], ["presentTelphone", "name", "patientId"]);

                unset($data["userInfo"]);
                $arr = [];
                foreach ($patientList as $k => $v) {
                    if (empty($v["presentTelphone"]) || is_null($v["presentTelphone"])) {
                        continue;
                    }
                    $data["patientId"] = $v["patientId"];
                    $data["content"] = $content;
                    $data["create_date"] = date("Y-m-d H:i:s");
                    $data["status"] = 0;
                    $data["patientName"] = $v["name"];
                    $data["message_topic"] = $templateInfo["sms_topic"];
                    $data["telephone"] = $v["presentTelphone"] ?? "";
                    $data["deleted_at"] = 0;
                    $patientIdArr[] = $v["patientId"];
                    $patientData = $data;
                    unset($v["users"]);
                    $arr[] = $patientData;
                    $telephoneArr[] = $data["telephone"];
                }
                $saveData = (new SmsRecord())->saveAll($arr);
                if ($saveData !== null) {
                    //执行批量发送短信
                    //$result = Sms::sendSms($telephoneArr, $content);
                    $result = \app\common\lib\Sms::getInstance()->sendMessage($telephoneArr, $content);
                    if (!empty($result) && $result["successCounts"] > 0) {
                        $status = 1;
                    } else {
                        $status = 2;
                    }
                    $ids = [];
                    foreach ($saveData as $sk => $sv) {
                        $ids[] = $sv["id"];
                    }
                    (new SmsRecord())->where("id", "in", $ids)->update([
                        "status" => $status,
                        "taskID" => $result["taskID"] ?? ""
                    ]);
                }

            } else {
                //todo 这里需要修改替换模板内容
                $content = $this->replaceContentTag($content, $templateInfo["model"], $match, $data["userInfo"], $businessData);

                $pattern = ' /(#.*#)/Ui';
                preg_match_all($pattern, $content, $matchChildren);

                if (!empty($matchChildren[0])) {

                    $content = $this->replaceContentTag($content, $templateInfo["model"], $matchChildren, $data["userInfo"], $businessData);
                }
                $patientList = (new PatientInfo())->getPatientListByUids($data["users"]);

                unset($data["users"]);
                foreach ($patientList as $k => $v) {
                    //替换患者模板变量
                    $newContent = $this->replaceContentPatientTag($content, $v);

                    $data["patientId"] = $v["patientId"];
                    $data["content"] = $newContent;
                    $data["create_date"] = date("Y-m-d H:i:s");
                    $data["status"] = 0;
                    $data["patientName"] = $v["name"];
                    $data["message_topic"] = $templateInfo["sms_topic"];
                    $data["telephone"] = $v["presentTelphone"];
                    $data["deleted_at"] = 0;
                    $data["task_id"] = is_array($data["task_id"]) ? $data["task_id"]['$oid'] : $data["task_id"];
                    $patientIdArr[] = $v["patientId"];
                    unset($data["userInfo"]);

                    $smsId = (new SmsRecord())->createBy($data);

                    //执行短信发送操作
                    if (!empty($smsId)) {
                        $result = \app\common\lib\Sms::getInstance()->sendMessage([$data["telephone"]], $newContent);

                        if (!empty($result) && $result["successCounts"] > 0) {
                            $status = 1;
                        } else {
                            $status = 2;
                        }
                        $rst = (new SmsRecord())->updateBy($smsId, [
                            "status" => $status,
                            "taskID" => $result["taskID"] ?? ""
                        ]);
                    }
                }
            }
        } catch (\Exception $exception) {

            \think\facade\Log::error("短信发送异常:" . $exception->getMessage());
            return false;
        } finally {
            try {

                $patientStatusArr = [];
                foreach ($patientIdArr as $k => $v) {
                    $patientStatusArr[] = ["patientId" => $v, "status" => $status];
                }
                //new PushResult($templateInfo["model"], $data["business_id"], $patientStatusArr);
                (new Message())->smsAbnormalInfo($data["model"] ?? $templateInfo["model"], (string)$data["task_id"], $patientStatusArr, $data["source"] ?? "随访计划");
            } catch (\Exception $exception) {
                echo $exception->getMessage();
                \think\facade\Log::error("记录回推异常:" . $exception->getMessage());
                return false;
            }


            return true;
        }
    }

    private function replaceContentTag(string $content, string $model, array $match, $userInfo, $businessData = [], $patientInfo = [])
    {

        try {
            if ($model !== "Common") {
                $result = (new SmsTag())->alias("t1")->whereOr([["model", "=", "Common"], ["model", "=", $model]])->catchLeftJoin(SmsTopic::class, "id", "sms_topic_id", ["model"])->field("t1.*")->select();
            } else {
                $result = (new SmsTag())->alias("t1")->where([["model", "=", "Common"]])->catchLeftJoin(SmsTopic::class, "id", "sms_topic_id", ["model"])->field("t1.*")->select();
            }
            $tagList = [];
            foreach ($result as $k => $v) {
                $tagList[$v["title"]] = [
                    "model" => $v["model"],
                    "mapping_field" => $v["mapping_field"],
                    "type" => $v["type"]
                ];
            }

            foreach ($match[0] as $k => $v) {
                $tag = $tagList[$v] ?? [];
                if (!empty($tag)) {
                    if ($tag["model"] === "Common" || $tag["type"] === 2) {
                        $mappingField = $tagList[$v]["mapping_field"];
                        if ($tagList[$v]["type"] === 1 && !empty($mappingField)) {
                            $content = str_replace($v, $userInfo[$mappingField], $content);
                        } else if ($tagList[$v]["type"] === 2) {
                            $content = str_replace($v, $tag["mapping_field"], $content);
                        }
                    } else {
                        $content = str_replace($v, $businessData[$tag["mapping_field"]] ?? "", $content);
                    }
                }
            }
            return $content;
        } catch (\Exception $exception) {
            return $content;
        }
    }

    private function replaceContentPatientTag($content, $patientInfo)
    {
        //判断模板中的内容是否需要转换变量操作
        try {

            $pattern = ' /(@.*@)/U';
            preg_match_all($pattern, $content, $match);
            if (!empty($match[0])) {
                $result = (new SmsTag())->where("type", "=", "3")->select();
                foreach ($result as $k => $v) {
                    $tagList[$v["title"]] = [
                        "model" => $v["model"],
                        "mapping_field" => $v["mapping_field"],
                        "type" => $v["type"]
                    ];
                }

                foreach ($match[0] as $k => $v) {
                    $tag = $tagList[$v] ?? [];
                    if (!empty($tag)) {
                        $value = $patientInfo[$tag["mapping_field"]] ?? "";
                        $content = str_replace($v, $value, $content);
                    }
                }
            }
            return $content;
        } catch (\Exception $exception) {
            return $content;
        }


    }


}